<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>

    <style> 
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }
      .main {
         position: relative;
         margin: 0 auto;
         margin-top: 50px;
         
      }
      .item, .selectItem {
        position: absolute;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1px solid #cccccc;
        transition: all .3s ease-in-out;
        z-index: 9999;
        border-radius: 10px;
        -webkit-backface-visibility: hidden;
        backface-visibility: hidden
      }
      .disable::after {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.6);
        border-radius: 10px;
      }
      .itemCollect {
        position: absolute;
        background-color: rgb(211, 211, 211);
        border: 1px solid #cccccc;
        left: 50%;
        transform: translateX(-50%);
        border-radius: 10px;
      }
    </style>
  </head>
  <body>
    <div class="main">
    </div>

    <script>
      //step0 数据准备
      const simpleData = [
        { name: "喜", color: "#FFA500" },
        { name: "美", color: "#00FF00" },
        { name: "懒", color: "#aa88cc" },
        { name: "沸", color: "#FFFF00" },
        { name: "慢", color: "#FF0000" },
        { name: "暖", color: "#00BBFF" },
      ];
      const size = 40;
      const row = 10;
      const col = 10;
      const oneGroup = 3;
      const Group = 6;
      const maxNum = oneGroup * 2;
      const layerCount = 5;
      const cellHtml = [];
      const assignedId = [];
      //注意，这里保证oneGroup * Group * simpleData.length <= row * col, 否则最后会消不干净
      const renderData = Array.from(new Array(oneGroup * Group)).map((v) => {
        return simpleData.map((item) => ({ ...item }));
      }).flat().sort(() => Math.random() - 0.5);

      //step1 创造小块方阵
      function createCell() {
        for(let layer = layerCount - 1; layer >= 0; layer-- ){
          const isDouble = layer % 2
          let offsetRow = 0, offsetCol = 0;
          if(isDouble) {
            offsetRow = size / 2;
            offsetCol = size / 2;
          }
          for(let i = 0; i < row; i++){
            for(let j = 0; j < col; j++) {
              const id = `m${layer}-${i}-${j}`;
              let item;
              if(Math.random() > 0.8 && assignedId.indexOf(id) >= 0){
                item = renderData.pop()
              }
              assignedId.push(id);
              if(item) {
                cellHtml.push(`<div class="item" id="${id}" onclick="onClick(this)" style="width:${size}px; height:${size}px; 
                top:${size*i + offsetRow}px; left:${size*j + offsetCol}px; background-color:${item.color};font-size:${size / 2}px;">${item.name}</div>`);
              }
            }
          }
        }
        if(renderData.length !== 0) {
          createCell()
        }
      }
      createCell()

      //对即将添加入main的dom进行排序，保证layer更低的在更后面，可以覆盖前面相同位置的dom
      const idReg = /id="([^"]+)"/;
      function matchLayer(item) {
        return idReg.exec(item)[1];
      }
      cellHtml.sort((a, b) => {
        const layerA = matchLayer(a).substring(1).split("-")[0];
        const layerB = matchLayer(b).substring(1).split("-")[0];
        return layerB - layerA;
      })

      //创造下面的收集框
      cellHtml.push(`<div class="itemCollect" style="width:${size * maxNum}px; height:${size}px; bottom:${0}px;"></div>`);


      //添加所有子dom到main中
      const main = document.querySelector(".main");
      main.style.width = `${size * col}px`;
      main.style.height = `${size * row + 2*size}px`;
      main.innerHTML = cellHtml.join(" ");

      //step2 判断哪些小块是被遮住的
      function isShadow(dom) {
        dom.querySelectorAll(".item").forEach(item => {
          let [layer, i, j] = item.id.substr(1).split("-").map(i => parseInt(i))
          const isDoubleNow = layer % 2;

          for(let k = layer - 1; k >= 0; k--) {
            const isDouble = k % 2;
            if(isDoubleNow !== isDouble) {
              if(isDoubleNow) {
                const blocks = [`#m${k}-${i+1}-${j}`, `#m${k}-${i+1}-${j+1}`, `#m${k}-${i}-${j+1}`, `#m${k}-${i}-${j}`]
                if(blocks.every(block => {
                  return !document.querySelector(block);
                })){
                  //移除disable
                  item.classList.remove("disable");
                }else {
                  //添加disable
                  item.classList.add("disable");
                  break;
                }
              }else {
                const blocks = [`#m${k}-${i-1}-${j}`, `#m${k}-${i-1}-${j-1}`, `#m${k}-${i}-${j-1}`, `#m${k}-${i}-${j}`]
                // const blocks = [`#m${k}-${i+1}-${j}`, `#m${k}-${i+1}-${j+1}`, `#m${k}-${i}-${j+1}`, `#m${k}-${i}-${j}`]

                if(blocks.every(block => {
                  return !document.querySelector(block);
                })){
                  //移除disable
                  item.classList.remove("disable");
                }else {
                  //添加disable
                  item.classList.add("disable");
                  break;
                }
              }
            }else {
              if(document.querySelector(`#m${k}-${i}-${j}`)) {
                item.classList.add("disable");
                break;
              }else {
                  item.classList.remove("disable");
              }
            }
          }
        });
      }
      isShadow(main)

      //step3 添加小块的点击事件
      const collect = document.querySelector(".itemCollect");
      function onClick(item) {
        if(item.id.split('-').slice(-1) == 'select' || item.classList.contains('disable')){
          return
        }
        item.classList.replace('item', 'selectItem');
        item.id = item.id + '-select';

        const offSetX = collect.offsetLeft - collect.offsetWidth / 2;
        const offSetY = collect.offsetTop;
        item.style.left = `${offSetX + size * (collect.children.length)}px`;
        item.style.top = `${offSetY - 1}px`;
        isShadow(main)
        item.addEventListener('transitionend', () => {
          item.style.left = `${size * (collect.children.length)}px`;
          item.style.top = `-1px`;
          collect.appendChild(item);

          clear(item)
        }, { once: true});
      } 

      //收集框内小块消除逻辑
      function clear(item) {
        const filterList = [...collect.children].filter(child => child.innerHTML == item.innerHTML)
        if(filterList.length >= oneGroup) {
          let count = filterList.length
          filterList.forEach(item => {
            item.style.scale = 0;
            item.addEventListener('transitionend', () => {
              collect.removeChild(item);

              count--;
              if(count === 0) {
                queueOrder()
                checkWin()
              }
            })
          })
        }else {
          checkWin()
        }
      }

      //收集框内小块位置逻辑
      function queueOrder() {
        [...collect.children].forEach((item, index) => {
          item.style.left = `${size * index}px`;
        })
      }

      //判断胜负
      function checkWin() {
        if(collect.children.length === maxNum) {
          alert("你输了！");
          return location.reload()
        }else if(main.children.length === 1) {
          alert("你赢了！");
          return location.reload()
        }
     }

    </script>
  </body>
</html>
